﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Milkify.Data;
using Milkify.Input;
using Milkify.Interfaces;

namespace Milkify.Views
{
    /// <summary>
    /// Interaction logic for TaskListListControl.xaml
    /// </summary>
    public partial class TaskListListControl : Page, IRefreshableView
    {
        private static readonly Key[] sIndexedTaskListShortcutGestures = new Key[10]
        {
            Key.D1, Key.D2, Key.D3, Key.D4, Key.D5, Key.D6, Key.D7, Key.D8, Key.D9, Key.D0
        };

        private PageFocusHelper mFocusHelper;
        private ICommand mIndexedTaskListShortcutCommand;

        public TaskListListControl()
        {
            InitializeComponent();

            mFocusHelper = new PageFocusHelper(this, ListTaskLists, "ButtonTaskList");

            mIndexedTaskListShortcutCommand = new DecoupledCommand<int>(ExecuteIndexedTaskListShortcutCommand, CanExecuteIndexedTaskListShortcutCommand);
            for (int i = 0; i < 10; i++)
            {
                AddIndexedTaskListShortcutBinding(i);
            }
        }

        private void AddIndexedTaskListShortcutBinding(int index)
        {
            var gesture = new GenericKeyGesture(sIndexedTaskListShortcutGestures[index]);
            var binding = new InputBinding(mIndexedTaskListShortcutCommand, gesture);
            binding.CommandParameter = index;
            InputBindings.Add(binding);
        }

        private void ButtonTaskList_Click(object sender, RoutedEventArgs e)
        {
            mFocusHelper.FocusElement = sender as IInputElement;
        }

        private void ExecuteIndexedTaskListShortcutCommand(int index)
        {
            var viewData = ViewData as TaskListListViewData;
            if (viewData != null &&
                viewData.NavigateToTaskListCommand != null &&
                viewData.TaskLists.Count > index)
                viewData.NavigateToTaskListCommand.Execute(viewData.TaskLists[index]);
        }

        private bool CanExecuteIndexedTaskListShortcutCommand(int index)
        {
            var viewData = ViewData as TaskListListViewData;
            if (viewData != null &&
                viewData.NavigateToTaskListCommand != null &&
                viewData.TaskLists.Count > index)
                return true;
            return false;
        }

        #region IView Members

        public object ViewData
        {
            get { return DataContext; }
            set { DataContext = value; }
        }

        #endregion

        #region IRefreshableView Members

        public bool NeedsRefresh { get; set; }

        #endregion
    }
}
